/*
 * @Author: zxc
 * @Date: 2021-01-23 14:27:00
 * @LastEditTime: 2021-01-23 15:03:36
 * @LastEditors: zxc
 * @Description: 高阶函数
 */

const forEach = (array, fn) => {
  for (let i = 0; i < array.length; i++) {
    fn(array[i])
  }
}

const filter = (array, fn) => {
  let results = []
  for (let i = 0; i < array.length; i++) {
    if (fn(array[i])) {
      results.push(array[i])
    }
  }
  return results
}

const makeFn = () => {
  let msg = "hello , this is a function , name is makeFn"
  return function () {
    console.log(msg)
  }
}

const once = fn => {
  let hasDone = false
  return function (...args) {
    if (!hasDone) {
      hasDone = true
      return fn.apply(this, args)
    }
  }
}

const map = (array, fn) => {
  let results = []
  for (let value of array) {
    results.push(fn(value))
  }
  return results
}

const every = (array, fn) => {
  let result = true
  for (let value of array) {
    result = fn(value)
    if (!result) {
      break
    }
  }
  return result
}

const some = (array, fn) => {
  let result = false
  for (let value of array) {
    result = fn(value)
    if (result) {
      break
    }
  }
  return result
}

//test

let arr = [1, 4, 5, 2, 5, 2]

// forEach(arr, x => console.log(x))

// console.log(filter(arr, x => x % 2 !== 0))

// const testMakeFn = makeFn()
// testMakeFn()
// makeFn()()

// const pay = once(money => console.log(`共支付${money}元`))
// pay(5)
// pay(5)
// pay(5)
// pay(5)
// pay(5)

// const testMap = map(arr, x => x ** 2)
// console.log(testMap)

// const testEvery = every(arr, x => x > 0)
// console.log(testEvery)

const testSome = some(arr, x => x % 2 === 0)
console.log(testSome)
